//
// Created by xili on 2024/9/11 21:24.
// GO BIG OR GO HOME.
//
#include "leetcode.h"

class Solution {
public:
    int findUnsortedSubarray(vector<int> &nums) {
        int n = nums.size();
        int left = -1;
        int right = n;
        int cur = nums[0];
        for (int i = 1; i < n; i++) {
            if (nums[i] < cur) {
                left = i;
            } else {
                cur = nums[i];
            }
        }
        cur = nums[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            if (nums[i] > cur) {
                right = i;
            } else {
                cur = nums[i];
            }
        }
        return max(0, left - right + 1);
    }
};